<template>
  <view class="container">
    <view class="inner">
      <view class="contentList">
        <view class="contentLi" :class="n.isThrough && 'contentLiThrough'" v-for="(n,i) in questionList" :key="i">
          <view class="contentLiTitle" @click="expandOne(n,i)">
            <!--标题-->
            <view class="titleText">
              <view class="titleText1">{{ n.title }}</view>
              <view class="titleText2">
                {{ _.size(n.answerList) > 0 ? `${(n.ansActIndex || 0) + 1}/${_.size(n.answerList)}` : '-/-' }}
              </view>
            </view>
            <view class="questionOpt" v-if="isOptMenuShow">
              <view title="复制" class="qIcon qIconCopy" @click.stop="titleCopy(n,i)"></view>
              <view title="通过" class="qIcon qIconThroughDis" :class="n.isThrough && 'qIconThrough'" @click.stop="itemOptWithKey(n,'isThrough')"></view>
              <view title="折叠" class="qIcon qIconClose" @click.stop="closedOne(n,i)"></view>
              <view title="置顶" class="qIcon qIconExpand" @click.stop="expandOne(n,i)"></view>
              <view title="删除" class="qIcon qIconDelete" @click.stop="removeOneAnswer(n,i)" v-if="_.includes(modelGet('userInfo.role'),'admin')"></view>
              <view title="添加" class="qIcon qIcon1" @click.stop="addOneAnswer(n,i)"></view>
              <view title="收藏" class="qIcon qIcon2" :class="n.isCollect && 'qIcon2Active'" @click.stop="itemOptWithKey(n,'isCollect')"></view>
            </view>
            <view class="questionOpt" v-else>
              <view title="收藏关注" class="qIcon qIcon2" :class="n.isCollect && 'qIcon2Active'" @click.stop="itemOptWithKey(n,'isCollect')"></view>
            </view>
          </view>

          <!--<view class="answerTabList" v-if="_.size(n.answerList)>0">
            <view class="answerTabLi" v-for="(nn,ii) in n.answerList" :class="(n.ansActIndex === ii) && 'answerTabLiActive'" @click="answerTabLiActive(nn,ii,n,i)">
              {{ ii }}
            </view>
          </view>-->

          <view class="answerLiActive" v-if="(_.size(n.answerList)>0) && n.expand">
            <view class="contentWrapper">
              <view v-html="n.answerList[n.ansActIndex||0].content" class="contentWrap contentPage"></view>
            </view>
            <!--标签-->
            <view class="labelList labelListWrap" v-if="isOptMenuShow">
              <view class="labelListInner">
                <view class="labelLi">......</view>
                <view class="labelLi" :class="_.includes(n.labels,labelInfo.label) && 'labelLiActive'" @click="questionLabelUpdate(n,labelInfo.label)" v-for="(labelInfo,labelIndex) in questionLabel" :key="labelIndex" :title="labelInfo.desc">
                  {{ labelInfo.label }}
                </view>
              </view>
            </view>
            <!--<view class="answerOpt">
              <view class="aOptMoreContent">
              </view>
              <view class="aOptBasic aOptPre"></view>
              <view class="aOptBasic aOptMore"></view>
              <view class="aOptBasic aOptNext"></view>
            </view>-->
            <!--操作按钮-->
            <view class="answerOptList">
              <!--前一个-->
              <view class="answerOptLi optBtn optPre" @click="ansActIndexSub(n)" v-if="_.size(n.answerList)>1"></view>
              <view class="answerOptLi" @click="scoreAdd(n.answerList[n.ansActIndex||0],n.ansActIndex||0,n,i)">认可</view>
              <view class="answerOptLi" @click="scoreSub(n.answerList[n.ansActIndex||0],n.ansActIndex||0,n,i)">否定</view>
              <view class="answerOptLi" @click="scoreRemove(n.answerList[n.ansActIndex||0],n.ansActIndex||0,n,i)" v-if="_.includes(modelGet('userInfo.role'),'admin')">
                删除
              </view>
              <view class="answerOptLi" @click="editOneAnswer(n.answerList[n.ansActIndex||0],n.ansActIndex||0,n,i)">修改
              </view>
              <!--后一个-->
              <view class="answerOptLi optBtn optNext" @click="ansActIndexAdd(n)" v-if="_.size(n.answerList)>1"></view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!--筛选模块-->
    <view class="modalCenter modalDetail" v-if="searchInputVisible">
      <view class="inner">
        <view class="innerHeader">
          <view class="title">过滤</view>
          <view class="closeBtn" @click="searchModalClose"></view>
        </view>
        <view class="innerBody" @click.stop="optNext">
          <view class="searchInputWrap" v-if="searchInputVisible">
            <view class="searchInputInner">
              <input type="text" class="searchInput" placeholder="问题关键字..." v-model="searchInput" @input="searchInputHandler"/>
              <view class="optSearchValueClear" @click="searchInputHide"></view>
            </view>
          </view>

          <view class="labelSearchList">
            <view class="labelSearchLi" @click="labelSearch(labelInfo.label)" v-for="(labelInfo,labelIndex) in questionLabel" :key="labelIndex" :title="labelInfo.desc">
              {{ labelInfo.label }}
            </view>
          </view>

        </view>
        <view class="innerFooter">
          <view class="btnBasic btnCancel" @click="searchModalClose">关闭</view>
        </view>
      </view>

    </view>


    <!--底部控制-->
    <view class="optListPage">
      <view title="新增问题及答案" class="optLiPage" @click="addOneQuestion">新增</view>
      <!--<view class="optLiPage" @click="testImage">测试</view>-->
      <view title="折叠所有" class="optLiPage" @click="expandAll">折叠</view>
      <view title="问题关键字搜索" class="optLiPage" @click="searchInputVisible = true">搜索</view>
      <view title="查看我的收藏" class="optLiPage" v-if="modelGet('userInfo._id')" :class="isShowMeCollect ? 'optLiPageNext' : ''" @click="showMeCollect">
        收藏
      </view>
      <view title="简易版本" class="optLiPage" :class="isOptMenuShow ? '' : 'optLiPageNext'" @click="isOptMenuShow = !isOptMenuShow">
        简版
      </view>
      <view class="optLiPage" @click="modelSet('home.modalLoginVisible',true)" v-if="!modelGet('userInfo._id')">
        登录
      </view>
      <view title="下一个问题滚到顶部" class="optLiPage" @click="scrollToNextQuestion">下一个</view>
    </view>
    <!--问题答案增删改-->
    <view class="modalCenter modalDetail" v-if="detailVisible">
      <view class="inner">
        <view class="innerHeader">
          <view class="title">{{ modalDetailInfo._id ? '修改' : '添加(问题|解答)' }}</view>
          <view class="closeBtn" @click="detailHide"></view>
        </view>
        <view class="innerBody" @click.stop="optNext">
          <input class="inputCommon" type="text" v-model="modalDetailInfo.questionTitle" @input="questionTitleChange" placeholder="问题"/>

          <!--类似问题-->
          <view class="likeQWrap" v-if="(likeQList.length > 0) && likeQListShow">
            <view class="likeQInner">
              <view class="likeQTitle">
                <view>类似问题</view>
                <view class="likeQListHideBtn" @click="likeQListShow = false"></view>
              </view>
              <view class="likeQList">
                <view class="likeQLi" v-for="(lq,lqIndex) in likeQList" :key="lqIndex" @click="lqClick(lq)">
                  {{ lq.title }}
                </view>
              </view>
            </view>
          </view>

          <!--<textarea class="textareaCommon" type="text" v-model="modalDetailInfo.source" placeholder="请输入..." maxlength="600"/>
          <editor id="editor" class="ql-container" placeholder="请输入..." @ready="onEditorReady" @input="editInputChange"></editor>-->

          <div contenteditable="true" class="contentWrap editorDiv" v-html="modalDetailInfo.content"></div>

          <view class="originInfo">
            <input class="inputCommon" type="text" v-model="modalDetailInfo.originLink" placeholder="解答来源地址"/>
            <input class="inputCommon" type="text" v-model="modalDetailInfo.originTitle" placeholder="解答来源标题"/>
          </view>

          <!--新增问题时展示(qId为空)-->
          <view class="labelList labelListWrap2" v-if="!modalDetailInfo.qId">
            <view class="labelListInner">
              <view class="labelLi" :class="_.includes(modalDetailInfo.labels,labelInfo.label) && 'labelLiActive'" @click="modalDetailInfoLabelsUpdate(modalDetailInfo,labelInfo.label)" v-for="(labelInfo,labelIndex) in questionLabel" :key="labelIndex" :title="labelInfo.desc">
                {{ labelInfo.label }}
              </view>
            </view>
          </view>

          <!--文本形式-->
          <view class="tabList">
            <view class="tabLi"
                v-for="(typeV,typeI) in answerTypeList"
                :key="typeI"
                :class="modalDetailInfo.type === typeV.value && 'tabLiActive'"
                @click="typeChange(typeV)"
            >
              {{ typeV.label }}
            </view>
          </view>
        </view>
        <view class="innerFooter">
          <view class="btnBasic btnCancel" @click="detailHide">取消</view>
          <view class="btnBasic btnConfirm" @click="inputCommit(true)">继续添加</view>
          <view class="btnBasic btnConfirm" @click="inputCommit()">确认</view>
        </view>
      </view>
    </view>

    <!--用户登录-->
    <!--登录-->
    <modal-login v-if="modelGet('home.modalLoginVisible')"></modal-login>

  </view>
</template>

<script>
import modalLogin from './modalLogin'
import $ from 'jquery'
import _ from 'lodash'
import { modelGet } from '../../store/modelOpt'

let pageNumber = 0
let pageNumberCollect = 0
let pageSize = 100

export default {
  components: {
    modalLogin,
  },
  onHide(){
    uni.setStorageSync('isOptMenuShow', this.isOptMenuShow)
  },
  data(){

    uni.createMediaQueryObserver(this).observe({
      minWidth: 500,  //页面最小宽度 375px
      // maxWidth: 500,  //页面宽度最大 500px
    }, matches => {
      console.log(`matches`, matches)
    })

    let isOptMenuShow = uni.getStorageSync('isOptMenuShow')
    isOptMenuShow = isOptMenuShow === '' ? true : isOptMenuShow // 默认值为true

    return {
      detailVisible: false,
      modalDetailInfo: {
        qId: '', // 问题_id
        type: '',// 回答载体
        originLink: '', // 来源
        originTitle: '',// 来源
        content: '',// 内容
      },
      answerTypeList: [
        { label: '链接', value: 'link' },
        { label: 'markdown', value: 'md' },
        { label: '文本', value: 'txt' },
        { label: 'HTML', value: 'html' },
      ],
      questionLabel: [
        /* * 作者：子弈 链接：https://juejin.cn/post/6987549240436195364 * */
        { label: '基础', value: '', desc: '计算机原理、编译原理、数据结构、算法、设计模式、编程范式等基本知识了解' },
        { label: '语法', value: '', desc: 'JavaScript、ECMAScript、CSS、TypeScript、HTML、Node.js 等语法的了解和使用' },
        { label: '框架', value: '', desc: 'React、Vue、Egg、Koa、Express、Webpack 等原理的了解和使用' },
        { label: 'React', value: '', desc: '' },
        { label: 'Vue', value: '', desc: '' },
        { label: 'Webpack', value: '', desc: '' },
        { label: 'Node', value: '', desc: '' },
        { label: 'CSS', value: '', desc: '' },
        { label: '工程', value: '', desc: '编译工具、格式工具、Git、NPM、单元测试、Nginx、PM2、CI / CD 了解和使用' },
        { label: '网络', value: '', desc: 'HTTP、TCP、UDP、WebSocket、Cookie、Session、跨域、缓存、协议的了解' },
        { label: '性能', value: '', desc: '编译性能、监控、白屏检测、SEO、Service Worker 等了解' },
        { label: '插件', value: '', desc: 'Chrome 、Vue CLI 、Webpack 等插件设计思路的理解' },
        { label: '系统', value: '', desc: 'Mac、Windows、Linux 系统配置的实践' },
        { label: '后端', value: '', desc: 'Redis 缓存、数据库、Graphql、SSR、模板引擎等了解和使用' },
      ],
      isShowMeCollect: false,// 是否展示收藏按钮

      isOptMenuShow: isOptMenuShow,// 是否是简化模式,展示更多操作按钮

      searchInput: '',
      searchInputVisible: false,

      searchLabel: '',

      href: 'https://uniapp.dcloud.io/component/README?id=uniui',
      questionList: [
        // {
        //   title: '11111111',
        //   ansActIndex: 0,
        //   answerList: [
        //     { content: '222222' },
        //     { content: '222222' },
        //     { content: '222222' },
        //   ],
        // },
      ],

      likeQList: [], // 在添加时搜索出来的类似值
      likeQListShow: false,
    }
  },
  created(){
    // 获取数据
    this.getDataNormal()
  },
  onReachBottom(){
    if (this.isShowMeCollect) {
      this.getDataCollect()
    } else {
      this.getDataNormal()
    }
  },
  methods: {
    searchInputHide(){
      this.searchInput = ''
      this.searchLabel = ''
      // this.searchInputVisible = false
      pageNumber = 0
      this.questionList = []

      this.getDataNormal()
    },
    labelSearch(label){
      this.searchInput = ''
      this.searchLabel = label
      this.searchInputVisible = false
      pageNumber = 0
      this.questionList = []

      this.getDataNormal()
    },
    searchInputHandler: _.debounce(function (e){
      this.searchLabel = ''
      pageNumber = 0
      this.questionList = []
      this.getDataNormal()
    }, 500),
    /*
    * 测试上传图片
    * */
    async testImage(){
      const result = await uniCloud.uploadFile({
        filePath: 'https://mmbiz.qpic.cn/mmbiz_png/8yYJbHq59icg6Kic7vvL3Sq5JYpm3Ya7LECibe4aTMIY0VoPibO0Jia8UQk46B1e11dWeraQ0L1AuCEG5OgRSAoYMWw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1',
        cloudPath: '222',
        onUploadProgress: function (progressEvent){
          let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        },
      })
      console.log(`result`, result)
    },
    titleCopy(n){

      // #ifdef MP-WEIXIN
      uni.setClipboardData({
        data: n.title,
        success: function (){
          this.util.message('已经复制问题~')
        },
      })
      // #endif
      // #ifdef H5
      let inputDom = document.createElement('input')
      inputDom.value = n.title
      document.body.appendChild(inputDom)
      inputDom.select()
      document.execCommand('Copy')
      document.body.removeChild(inputDom)
      this.util.message('已经复制问题~')
      // #endif

    },
    editInputChange(e){
      console.log(`e`, e)
    },
    async getDataCollect(){
      let util = this.util
      let $ = util.dbCmd.aggregate

      let userInfo = this.modelGet('userInfo')

      if (_.isNil(userInfo._id)) {
        util.message('请登录~')
        return
      }


      util.uniDB('qd-user-opt')
          .aggregate() // 获取数据库集合的聚合操作实例
          .match({
            userId: userInfo._id,
            isCollect: true,
          })
          .skip(pageNumberCollect * pageSize).limit(pageSize)
          .lookup({
            from: 'qd-question',
            let: {
              'a_qId': '$qId',
            },
            pipeline: $.pipeline().match(util.dbCmd.expr($.eq(['$_id', '$$a_qId']))).done(),
            as: 'questionList',
          })
          .lookup({
            from: 'qd-answer',
            let: {
              'a_qId': '$qId',
            },
            pipeline: $.pipeline().match(util.dbCmd.expr($.eq(['$qId', '$$a_qId']))).match({
              score: util.dbCmd.gte(0).or(util.dbCmd.eq(null)),// 分数为空,或者大于等于0
            }).done(),
            as: 'answerList',
          })
          // .addFields({ // 添加字段
          //   ansActIndex: 0, // 第一个元素默认获焦
          //   expand: false, // 默认都展开
          // })
          .end()
          .then((res) => {
            console.log(`res`, res)
            if (_.size(res.result.data) > 0) {
              let dataNext = _.map(_.filter(res.result.data, (n, i) => {
                return _.size(n.questionList) > 0
              }), (n, i) => {
                let questionInfo = n.questionList[0]
                return {
                  answerList: n.answerList,
                  isCollect: true,
                  ansActIndex: 0, // 第一个元素默认获焦
                  expand: false, // 默认都展开
                  ...questionInfo,
                }
              })

              console.log(`dataNext`, dataNext)
              this.questionList = this.questionList.concat(dataNext)
              pageNumberCollect++
            } else {
              // this.util.message('已经遍历所有题目')
              // pageNumberCollect = 0
            }
          })
    },
    async getDataNormal(){
      try {
        await modelGet('loginPromise') // 等待登录执行完毕
      } catch (e) {
        console.log(`e`, e)
      }
      let userInfo = this.modelGet('userInfo')
      console.log(`userInfo`, userInfo)
      let util = this.util
      let $ = util.dbCmd.aggregate

      // util.uniDB('qd-question').get().then((res) => {
      //   console.log(`res`, res)
      // })

      let matchObj = {}
      if (this.searchInput) {
        matchObj.title = new RegExp(this.searchInput, 'i')
      }
      if (this.searchLabel) {
        matchObj.labels = this.searchLabel // util.dbCmd.all([this.searchLabel])
      }
      console.log(`搜索条件: `, this.searchInput, this.searchLabel)
      util.uniDB('qd-question')
          .aggregate() // 获取数据库集合的聚合操作实例
          .match(matchObj)
          // .match({
          //   // commitUserId: this.onlyMine ? util.dbCmd.eq(userInfo._id) : util.dbCmd.neq(userInfo._id), // 是否是自己
          //   // reviewerRes: this.onlyMine ? null : util.dbCmd.not(util.dbCmd.elemMatch({ userId: userInfo._id })),// 我审核过的就不再出现
          //   // 普通数组: util.dbCmd.not(util.dbCmd.all([userInfo._id]))
          //   // 对象数组: util.dbCmd.not(util.dbCmd.all([userInfo._id]))
          //
          //   // originInfoId: this.filterType === 'update' ? util.dbCmd.neq(null) : util.dbCmd.eq(null),// originInfoId 有值则代表是修改,无值则代表是新增
          //   title: new RegExp(this.searchInput, 'i'),
          // })
          .skip(pageNumber * pageSize).limit(pageSize)
          .lookup({
            from: 'qd-answer',
            let: {
              'a_id': '$_id',
            },
            pipeline: $.pipeline().match(util.dbCmd.expr($.eq(['$qId', '$$a_id']))).match({
              score: util.dbCmd.gte(0).or(util.dbCmd.eq(null)),// 分数为空,或者大于等于0
            }).done(),
            as: 'answerList',
          })
          .lookup({
            from: 'qd-user-opt',
            let: {
              'a_id': '$_id',
            },
            pipeline: $.pipeline().match(util.dbCmd.expr($.eq(['$qId', '$$a_id']))).match({
              userId: util.dbCmd.eq(userInfo._id),// 当前用户
              // isCollect: true,
            }).done(),
            as: 'userOptList',
          })
          .addFields({ // 添加字段
            userOpt: $.arrayElemAt(['$userOptList', 0]), // 注意_id覆盖问题
          })
          .addFields({ // 添加字段(页面使用)
            ansActIndex: 0, // 第一个元素默认获焦
            expand: false, // 默认都展开
          })
          // .project({ // 去除字段
          //   originquestionList: false,
          // })
          // .lookup({
          //   from: 'juzi-collect',
          //   localField: 'originInfoId',
          //   foreignField: '_id',
          //   as: 'originInfo',
          // })
          .end()
          .then(res => res.result.data)
          .then(data => {
            console.log(`data`, data)
            if (_.size(data) > 0) {
              let dataNext = _.map(data, (n, i) => ({
                ...n.userOpt, // isCollect isThrough qId userId _id
                ...n,
              }))
              this.questionList = this.questionList.concat(dataNext)
              pageNumber++
            } else {
              this.util.message('已经遍历所有题目')
              // pageNumber = 0
            }
          })
          .catch(err => {
            console.error(err)
          })
    },
    onEditorReady(){
      // #ifdef MP-BAIDU
      this.editorCtx = requireDynamicLib('editorLib').createEditorContext('editorId')
      // #endif

      // #ifdef APP-PLUS || H5 ||MP-WEIXIN
      uni.createSelectorQuery().select('#editor').context((res) => {
        this.editorCtx = res.context
        console.log(`this.editorCtx`, this.editorCtx)
      }).exec()
      // #endif
    },
    detailHide(){
      this.detailVisible = false
      this.likeQList = []
    },
    searchModalClose(){
      this.searchInputVisible = false
    },
    optNext(){
      console.log(`optNext`, 1)
    },
    /*
    * 确认,提交
    * isNext: 是否需要继续添加
    * */
    inputCommit(isNext){
      $('.editorDiv pre[data-tool="mdnice编辑器"]>span:first-child').remove() // 删除代码框中 ... 简书的代码框
      $('.editorDiv button[aria-label="复制代码"]').remove() // 复制代码按钮删除

      $('.editorDiv>h1').attr('style', '')
      $('.editorDiv>h2').attr('style', '')
      $('.editorDiv>h3').attr('style', '')
      $('.editorDiv>p').attr('style', '')
      $('.editorDiv pre').attr('style', '')
      $('.editorDiv>blockquote').attr('style', '')
      $('.editorDiv>hr').attr('style', '')
      $('.editorDiv>ul').attr('style', '')
      $('.editorDiv>ul>li').attr('style', '')

      $('.editorDiv')[0].innerHTML = $('.editorDiv')[0].innerHTML.replace(/font-size\:\s+\w+/gi, '') // 去除所有字体大小控制

      let content = document.querySelector('.editorDiv').innerHTML

      if (this.modalDetailInfo.qId) { // 已有问题
        if (this.modalDetailInfo._id) {// 修改
          console.log(`this.modalDetailInfo._id`, this.modalDetailInfo)
          this.util.uniDB('qd-answer').doc(this.modalDetailInfo._id).update({
            type: this.modalDetailInfo.type,// 回答载体
            originLink: this.modalDetailInfo.originLink, // 来源
            originTitle: this.modalDetailInfo.originTitle,// 来源
            content: content,
          }).then((res) => {
            this.questionList[this.editIndexQ].answerList[this.editIndexA].content = content // 同步信息到主页
            this.util.message('√')
          })

          if (this.questionList[this.editIndexQ].title !== this.modalDetailInfo.questionTitle) {
            this.util.uniDB('qd-question').doc(this.modalDetailInfo.qId).update({
              title: this.modalDetailInfo.questionTitle,
            }).then((res) => {
              this.questionList[this.editIndexQ].title = this.modalDetailInfo.questionTitle
            })
          }

        } else {// 问题新增回答
          this.util.uniDB('qd-answer').add({
            qId: this.modalDetailInfo.qId,
            type: this.modalDetailInfo.type,// 回答载体
            originLink: this.modalDetailInfo.originLink, // 来源
            originTitle: this.modalDetailInfo.originTitle,// 来源
            content: content,
            score: 0,
          }).then((res) => {
            this.questionList[this.editIndexQ].answerList.push({
              _id: res.result.id,
              ...this.modalDetailInfo,
              content: content,
            })
            this.util.message('√')
          })
        }
      } else {// 新增问题[回答]
        this.util.uniDB('qd-question').add({
          title: this.modalDetailInfo.questionTitle,
          labels: this.modalDetailInfo.labels,
        }).then((res) => {
          console.log(`res`, res)
          let qId = res.result.id
          this.questionList.push({
            _id: qId,
            title: this.modalDetailInfo.questionTitle,
            labels: this.modalDetailInfo.labels,
            ansActIndex: 0, // 第一个元素默认获焦
            expand: true, // 默认都展开
            answerList: [],
          })

          if (_.size(content) < 10) {// 解答文字不少于10个字
            return
          }

          let answerInfo = {
            qId,
            type: this.modalDetailInfo.type,// 回答载体
            originLink: this.modalDetailInfo.originLink, // 来源
            originTitle: this.modalDetailInfo.originTitle,// 来源
            content: content,
            score: 0,
          }

          this.util.uniDB('qd-answer').add(answerInfo).then((res) => {
            _.last(this.questionList).answerList.push({
              _id: res.result.id,
              ...answerInfo,
            })

            if (isNext) { // 是否继续添加
              this.addOneQuestion()
            }
          })
        })
      }

      this.detailVisible = false
    },
    addOneQuestion(){
      this.detailVisible = true
      this.modalDetailInfo = {
        questionTitle: '',
        content: '',
        labels: [],
        type: 'html',
      }
    },
    removeOneAnswer(n, i){
      this.util.uniDB('qd-question').where({ _id: n._id }).remove().then((res) => {
        console.log(`res`, res)
        this.util.message('删除问题成功!')

        this.questionList.splice(i, 1)

        this.util.uniDB('qd-answer').where({ qId: n._id }).remove().then((res) => {
          console.log(`res`, res)
          this.util.message(`删除${res.result.deleted}个问题~`)
        })
      })
    },
    addOneAnswer(n, i){
      this.detailVisible = true
      this.editIndexQ = i
      this.modalDetailInfo = {
        questionTitle: n.title,
        qId: n._id,
        content: '',
        labels: n.labels,
        type: 'html',
      }
    },
    scoreAdd(nn, ii, n, i){
      this.util.uniDB('qd-answer').doc(nn._id).update({
        score: (nn.score || 0) + 1,
      })
    },
    scoreSub(nn, ii, n, i){
      this.util.uniDB('qd-answer').doc(nn._id).update({
        score: (nn.score || 0) - 1,
      })
    },
    scoreRemove(nn, ii, n, i){
      this.util.uniDB('qd-answer').doc(nn._id).remove().then((res) => {
        this.ansActIndexAdd(n)
      })
    },
    editOneAnswer(nn, ii, n, i){
      this.detailVisible = true
      this.editIndexQ = i
      this.editIndexA = ii
      this.modalDetailInfo = {
        qId: n._id,
        questionTitle: n.title,
        labels: n.labels,
        ...nn,
      }
    },
    typeChange(typeInfo){
      console.log(`typeInfo`, typeInfo)
      this.modalDetailInfo.type = typeInfo.value
    },
    answerTabLiActive(nn, ii, n, i){
      this.$set(this.questionList[i], 'ansActIndex', ii)
    },
    scrollToNextQuestion(){
      const query = uni.createSelectorQuery()
      query.selectAll('.contentLi').boundingClientRect(data => {
        let curIndex = _.findIndex(data, (n, i) => {
          return n.top > 0
        })
        let nextScrollTop = _.sum(_.map(_.slice(data, 0, curIndex + 1), 'height')) + 10 + 10 * curIndex
        this.questionList[curIndex + 1].expand = true // 内容展开
        this.$nextTick(() => { // 滚动到相应位置
          uni.pageScrollTo({
            scrollTop: nextScrollTop,
            duration: 300,
          })
        })
      }).exec()
    },
    ansActIndexSub(n){
      n.ansActIndex--
      if (n.ansActIndex < 0) {
        n.ansActIndex = _.size(n.answerList) + n.ansActIndex
      }
    },
    ansActIndexAdd(n){
      n.ansActIndex++
      if (n.ansActIndex >= _.size(n.answerList)) {
        n.ansActIndex = n.ansActIndex - _.size(n.answerList)
      }
    },

    /**
     * 收藏|点赞 - 增加|减少
     * @param item
     * @param updateKey string 类型 collect like
     */
    async itemOptWithKey(item, updateKey){

      console.log(`item, updateKey`, item, updateKey)

      let that
      // #ifdef MP-WEIXIN
      that = this.$parent || this
      // #endif
      // #ifdef H5
      that = this
      // #endif

      let userInfo = that.modelGet('userInfo')

      if (!userInfo._id) {
        this.util.message('请先登录~')
        return
      }

      let updateInfo = {
        [updateKey]: !item[updateKey],
      }
      item[updateKey] = !item[updateKey]
      this.$forceUpdate()

      // if (that.modelGet('homeConfig.modalShareVisible')) {// 更新1: 模态框数据modalDetailInfo 更新2: 页面数据 wordList[homeConfig.modalDetailInfoIndex]
      //   // that.modelSet(`homeConfig.modalDetailInfo.${updateKey}`, item[updateKey]) // 无效 原先无updateKey字段则无效,原先肯定有modalDetailInfo字段
      //   // that.modelSet(`homeConfig.modalDetailInfo`, item) // 无效 需要传一个新对象,用以对比
      //   // that.modelSet(`homeConfig.modalDetailInfo`, {  isLike: true }) // 可以
      //   // that.modelSet(`homeConfig.modalDetailInfo`, JSON.parse(JSON.stringify(item))) // 可以
      //   that.modelSet(`homeConfig.modalDetailInfo`, { ...item }) // 或者使用 _.cloneDeep
      //
      //   that.modelSet(`wordList[${that.modelGet('homeConfig.modalDetailInfoIndex')}]`, { ...item }) // 或者使用 _.cloneDeep
      // }

      if (item[updateKey]) {
        let messageTip = {
          'isDeny': '将折叠隐藏此句~',
          'isError': '提醒主编有误~',
          'isCollect': '收藏成功~',
        }[updateKey]
        messageTip && this.util.message(messageTip, 500)
      }

      let [info] = await this.util.uniDB('qd-user-opt')
          .where({ userId: userInfo._id, qId: item._id })
          .get()
          .then((res) => res.result.data)

      if (info) {// 修改
        this.util.uniDB('qd-user-opt').doc(info._id).update(updateInfo)
      } else {// 新增
        this.util.uniDB('qd-user-opt').add({
          userId: userInfo._id,
          qId: item._id,
          ...updateInfo,
        })
      }

      // 统计此问题操作次数
      // 暂不支持客户端使用更新操作符,故计算后重置字段值
      // util.uniDB('juzi-dict').doc(item.wordId).update({ [`${updateKey}Num`]: util.dbCmd.inc(item[updateKey] ? 1 : -1) })
      let changeValue = item[updateKey] ? 1 : -1
      let changeInfo = { [`${updateKey}Num`]: (item[`${updateKey}Num`] || 0) + changeValue }
      this.util.uniDB('qd-question').doc(item._id).update(changeInfo) // isCollectNum isLikeNum
    },
    async modalDetailInfoLabelsUpdate(item, label){
      if (_.isNil(item.labels)) {
        this.$set(item, 'labels', [])
      }
      if (_.includes(item.labels, label)) {
        item.labels = _.without(item.labels, label)
      } else {
        item.labels.push(label)
      }
    },
    async questionLabelUpdate(item, label){
      if (_.isNil(item.labels)) {
        this.$set(item, 'labels', [])
      }
      if (_.includes(item.labels, label)) {
        item.labels = _.without(item.labels, label)
      } else {
        item.labels.push(label)
      }
      this.util.uniDB('qd-question').doc(item._id).update({
        labels: item.labels,
      }).then((res) => {
        console.log(`res`, res)
      })
    },
    /*
    * 1. 只提取英文单词
    *   描述vue react 区别
    * 2. 以3个字数为单位划分:
    *   value.replace(/(\S)(?=(?:\S{3})+$)/g, '$1|') // abcdefgh=>ab|cde|fgh
    * */
    splitStringToRegStr(str){
      let reArr = str.match(/[a-z|A-Z]+/gi) || [] // null  [react,vue]
      _.each(str.match(/[\u4e00-\u9fa5]+/gi) || [], (n, i) => {
        reArr.push.apply(reArr, n.split(/是|与|或|的|及|和|中|区别|比较|原理|什么|如何|谈谈|描述|介绍下|请|有|聊聊/gi) || [])
      })
      return _.filter(reArr, (n) => {
        return n.length > 1
      }).join('|')
    },
    questionTitleChange(e){
      let value = e.detail.value
      let regStr = this.splitStringToRegStr(value)
      console.log(`regStr`, regStr)
      if (regStr.length > 1) {
        // 查看是否有类似的问题
        this.util.uniDB('qd-question')
            .where({ title: new RegExp(regStr, 'gi') })
            .get().then(res => res.result.data)
            .then((res) => {
              this.likeQList = _.slice(res, 0, 10)
              this.likeQListShow = true
            })
      }

    },
    showMeCollect(){
      this.questionList = []
      this.isShowMeCollect = !this.isShowMeCollect
      if (this.isShowMeCollect) {
        pageNumberCollect = 0
        this.getDataCollect()
      } else {
        pageNumber = 0
        this.getDataNormal()
      }
    },
    expandAll(){
      _.each(this.questionList, (n, i) => {
        n.expand = false
      })
    },
    scrollItemTop(curIndex){
      const query = uni.createSelectorQuery()
      query.selectAll('.contentLi').boundingClientRect(data => {
        // let curIndex = _.findIndex(data, (n, i) => {
        //   return n.top > 0
        // })
        console.log(`curIndex`, curIndex)
        let nextScrollTop = _.sum(_.map(_.slice(data, 0, curIndex), 'height')) + 10 * curIndex // 前面各个内容高度总和 + 间隙
        console.log(`nextScrollTop`, nextScrollTop)
        uni.pageScrollTo({
          scrollTop: nextScrollTop,
          duration: 100,
        })
      }).exec()
    },
    expandOneOnly(n, i){
      _.each(this.questionList, (nn, ii) => {
        nn.expand = i === ii
        console.log(`n.expand`, n.expand)
      })
      this.$nextTick(() => {
        this.scrollItemTop(i)
      })
    },
    closedOne(n, i){
      n.expand = false
    },
    expandOne(n, i){
      n.expand = true
      this.$nextTick(() => {
        this.scrollItemTop(i)
      })
    },
    lqClick(n){
      console.log(`n`, n)
      let findIndex = _.findIndex(this.questionList, { _id: n._id })
      console.log(`findIndex`, findIndex)

      if (findIndex > -1) {
        this.expandOne(this.questionList[findIndex], findIndex)
        this.detailHide()
        return
      }

      let util = this.util
      let $ = util.dbCmd.aggregate
      util.uniDB('qd-question')
          .aggregate() // 获取数据库集合的聚合操作实例
          .match({
            _id: n._id,
          })
          .skip(0).limit(1)
          .lookup({
            from: 'qd-answer',
            let: {
              'a_id': '$_id',
            },
            pipeline: $.pipeline().match(util.dbCmd.expr($.eq(['$qId', '$$a_id']))).done(),
            as: 'answerList',
          })
          .addFields({ // 添加字段
            ansActIndex: 0, // 第一个元素默认获焦
            expand: true, // 默认都展开
          })
          .end()
          .then(res => res.result.data)
          .then(res => {
            if (_.size(res) > 0) {
              this.questionList.splice(0, 0, res[0])
              this.detailHide()
            }
          })
          .catch(err => {
            console.error(err)
          })

    },
  },
}
</script>

<style lang="scss">
@import "./index.scss";
@import "./article.scss";
</style>
